package com.lzx.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Map;

/**
 * Created by lizhenxing on 2017/4/19.
 */
@Slf4j
public class FormatUtil {

    private static ObjectMapper mapper = new ObjectMapper();

    static {
        mapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true)
                .configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true);

    }

    public static String toJson(Object o) {
        try {
            return mapper.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            log.error("converse obj to json encounter error.", e);
            return null;
        }
    }

    public static Map<? extends Object, ? extends Object> toMap(Object o, Class<Map<? extends Object, ? extends Object>> type) {
        return mapper.convertValue(o, type);
    }

    public static <T> T fromObj(Object o, Class<T> clazz) {
        try {
            return mapper.readValue(toJson(mapper.convertValue(o.toString(), Map.class)), clazz);
        } catch (Exception e) {
            log.error("converse obj to type: [{}]" + clazz.getName() + " encounter error.", e);
            return null;
        }
    }

    public static <T> T fromJson(String json, Class<T> clazz) {
        try {
            return mapper.readValue(json, clazz);
        } catch (IOException e) {
            log.error("converse json to type: [{}]" + clazz.getName() + " encounter error.", e);
            return null;
        }
    }
}
